namespace Billing2
{
    using AjaxControlToolkit;
    using System;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using Microsoft.Security.Application;
    using System.Web;
    using System.Web.Security;
    using MyLib;

    public class MasterPage : System.Web.UI.MasterPage
    {
        protected ContentPlaceHolder ContentPlaceHolder1;
        protected HtmlForm form1;
        protected ContentPlaceHolder head;
        protected Image ImgSiteImage;
        protected Label lblCurrentDateTime;
        protected Label lblFooter;
        protected Label lblGroupName;
        protected Label lblHeader;
        protected Label lblloginName;
        protected ScriptManager ScriptManager1;
        protected TreeView TreeView1;
        protected HiddenField request_id;

        private void BindTree()
        {
            if (LoginUser.TreeMenu != null)
            {
                new ClsTreeHelper { PageName = this.Page.ToString().Substring(4, this.Page.ToString().Substring(4).Length - 5) + ".aspx", dt = LoginUser.TreeMenu, controlTreeView = this.TreeView1 }.AddTree(0, null);
            }
            else
            {
                base.Response.Redirect("default.aspx", true);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Response.AppendHeader("Cache-Control", "no-store");
            this.Response.AppendHeader("Cache-Control", "no-cache");        
            this.Response.AppendHeader("X-Content-Type-Options", "nosniff");
            this.Response.AppendHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
#if !DEV
            this.Response.AppendHeader("Content-Security-policy", "default-src https: data: 'unsafe-inline' 'unsafe-eval'");
#endif

            if (base.Session["SiteID"] == null)
            {
                if (!IsPostBack)
                {
                    this.Session.Clear();
                    this.Session.Abandon();
                    FormsAuthentication.SignOut();
                    HttpContext.Current.Session.Abandon();
                    HttpCookie cookie = new HttpCookie("ASP.NET_SessionId", "");
                    cookie.Secure = true;
                    cookie.HttpOnly = true;
                    Response.Cookies.Add(cookie);
                }
                base.Response.Redirect("default.aspx", true);
            }

            //anti CSRF
            if (!this.Page.IsPostBack)
            {
                string anti_csrf = ClsPasswordHelper.Encrypt("anti_csrf" + MyLib.Rand.RandomInt(0, int.MaxValue - 1).ToString()).Replace("=", "").Replace("/", "").Replace("+", "");
                this.request_id.Value = anti_csrf;
                this.Session["request_id"] = anti_csrf;
            }
            else
            {
                if (this.Session["request_id"] == null || this.request_id.Value != this.Session["request_id"].ToString())
                {
                    EPPLog.Logger.Error(Common.EscapeLog(String.Format("Detecterd CSRF1. RawUrl={0} request_id={1} inSession={2}", this.Request.RawUrl, this.request_id.Value, this.Session["request_id"])));
                    base.Response.Redirect("logout.aspx", true);
                    return;
                }
            }

            //string token = this.Request.QueryString["token"] ?? "";
            //if (!Common.ValidToken(token))
            //{
            //    EPPLog.Logger.Error(String.Format("Detecterd CSRF2. RawUrl={0} token={1} sessionId={2}", this.Request.RawUrl, token, Common.GetSessionID()));
            //    base.Response.Redirect("default.aspx", true);
            //    return;
            //}

            if (!this.Page.IsPostBack)
            {
                this.lblHeader.Text = Microsoft.Security.Application.Encoder.HtmlEncode(ClsApplicationConfiguration.Header);
                //this.lblFooter.Text = Microsoft.Security.Application.Encoder.HtmlEncode(ClsApplicationConfiguration.Footer);
                this.BindTree();
                this.lblGroupName.Text = Microsoft.Security.Application.Encoder.HtmlEncode(LoginUser.GroupName);
                this.lblloginName.Text = Microsoft.Security.Application.Encoder.HtmlEncode(LoginUser.DisplayName);
                this.lblCurrentDateTime.Text = Microsoft.Security.Application.Encoder.HtmlEncode(LoginUser.CurrentLoginDateTime);
            }

            string referrer = this.Request.UrlReferrer == null ? "" : this.Request.UrlReferrer.ToString();
            if (!Global.IsAllowDomain(referrer))
            {
                EPPLog.Logger.Error(String.Format("Detecterd CSRF at MasterPage.Master. referrer={0}", Common.EscapeLog(referrer)));
                base.Response.Redirect("default.aspx", true);
                return;
            }

            //if (this.Page.ViewStateUserKey != Session.SessionID)
            //{
            //    this.Session.Clear();
            //    this.Session.Abandon();
            //    FormsAuthentication.SignOut();
            //    HttpContext.Current.Session.Abandon();
            //    HttpCookie cookie = new HttpCookie("ASP.NET_SessionId", "");
            //    cookie.Secure = true;
            //    cookie.HttpOnly = true;
            //    Response.Cookies.Add(cookie);
            //    base.Response.Redirect("default.aspx", true);
            //}

            if (Global.FindLoginLog(LoginUser.LoginID).session_id != this.Session.SessionID)
            {
                Session.Abandon();
                base.Response.Redirect("default.aspx", true);
                return;
            }
        }

        protected void Page_PreInit(object sender, EventArgs e)
        {
            //try
            //{
            //    //string IsLogin = LoginUser.LoginID;
            //}
            //catch
            //{
            //    base.Response.Redirect("default.aspx", true);
            //}
        }
        
        protected override void OnPreRender(EventArgs e)
        {
            //this.Page.ViewStateEncryptionMode = ViewStateEncryptionMode.Always;
            this.Page.RegisterRequiresViewStateEncryption();
            base.OnPreRender(e);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            try
            {
                //string IsLogin = LoginUser.LoginID;
                Page.ViewStateUserKey = Session.SessionID;
            }
            catch (TimeoutException e2)
            {
                EPPLog.Logger.Error(e2);
                base.Response.Redirect("default.aspx", true);
            }
            catch (Exception ex)
            {
                EPPLog.Logger.Error(ex);
                base.Response.Redirect("default.aspx", true);
            }
        }
    }
}
